package com.maomi.coder;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lucky on 2019-03-29.
 */
public class FilterDemo {

    public static void main(String[] args) throws IOException {
        String text = "这个 番茄 真好吃。 今天吃了 土豆 炒牛肉和烤 地瓜";
        Analyzer analyzer = new WhitespaceAnalyzer();

        AnalyzerFilter analyzerFilter = new AnalyzerFilter(analyzer.tokenStream("text",text));

        CharTermAttribute attribute = analyzerFilter.addAttribute(CharTermAttribute.class);

        analyzerFilter.reset();

        while (analyzerFilter.incrementToken()){
            System.out.print(attribute);
        }
    }

    static class AnalyzerFilter extends TokenFilter{

        private CharTermAttribute attribute;

        private Map<String,String> map;

        protected AnalyzerFilter(TokenStream input) {
            super(input);
            attribute = addAttribute(CharTermAttribute.class);
            map= new HashMap<>();
            map.put("番茄","西红柿");
            map.put("土豆","马铃薯");
            map.put("地瓜","红薯");
        }

        @Override
        public boolean incrementToken() throws IOException {
            if(!input.incrementToken()){
                return false;
            }
            String s = attribute.toString();
            if(map.containsKey(s)){
                attribute.setEmpty().append(map.get(s));
            }
            return true;
        }
    }
}
